##############################################################################
#
# Copyright (c) 2007 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
import sys
import logging, os, shutil, tempfile, urllib2, urlparse
import setuptools.archive_util
import zc.buildout
import zc.recipe.egg

class Recipe:

    def __init__(self, buildout, name, options):
        self.egg = zc.recipe.egg.Egg(buildout, options['recipe'], options)
        self.logger = logging.getLogger(name)
        self.buildout, self.name, self.options = buildout, name, options
        options['location'] = options['prefix'] = os.path.join(
            buildout['buildout']['parts-directory'],
            name)

        # We look for a download directory, where we put the download tarballs
        # This is the same as the gocept.download and zope2install recipes use
        buildout['buildout'].setdefault(
            'download-directory',
            os.path.join(buildout['buildout']['directory'], 'downloads'))
        seleniumpythonpath =  os.path.join(options['location'],'seleniumpython')
        options['seleniumpythonpath'] = seleniumpythonpath
        options['eggs'] = 'seleniumrcconfig'

    def install(self):
        dest = self.options['location']
        seleniumrcdist = self.options['seleniumrcdist']
        download_dir = self.buildout['buildout']['download-directory']
        if not os.path.isdir(download_dir):
            os.mkdir(download_dir)
            self.options.created(download_dir)

        if os.path.exists(dest):
            shutil.rmtree(dest)
        os.mkdir(dest)

        url = seleniumrcdist
        _, _, urlpath, _, _, _ = urlparse.urlparse(url)
        tmp = tempfile.mkdtemp('buildout-'+self.name)
        try:
            fname = os.path.join(download_dir, urlpath.split('/')[-1])
            # Have we already downloaded the file
            if not os.path.exists(fname):
                f = open(fname, 'wb')
                try:
                    f.write(urllib2.urlopen(url).read())
                except Exception, e:
                    os.remove(fname)
                    raise zc.buildout.UserError(
                        "Failed to download URL %s: %s" % (url, str(e)))
                f.close()
            setuptools.archive_util.unpack_archive(fname, dest)
        finally:
            shutil.rmtree(tmp)

        files = setuptools.findall(dest)
        seleniumpymodule = [x for x in files if 'selenium.py' in x][0]
        seleniumpypath = os.path.dirname(os.path.realpath(seleniumpymodule))
        seleniumserverjar = [x for x in files if 'selenium-server.jar' in x][0]

        seleniumrcconfigpath = os.path.join(self.options['location'],'seleniumrcconfig.py')
        seleniumrcinitpath = os.path.join(self.options['location'],'__init__.py')
        seleniumrcsetuppath = os.path.join(self.options['location'],'setup.py')
        javabin =  self.options.get('javabin','java')

        confpy = open(seleniumrcconfigpath,'w')
        confpy.write('seleniumpythonpath="%s" %s' %(seleniumpypath, os.linesep))
        confpy.write('seleniumserverjar="%s" %s' %(seleniumserverjar, os.linesep))
        confpy.write('javabinary="%s" %s' %(javabin, os.linesep))
        confpy.close()

        initpy = open(seleniumrcinitpath,'w')
        initpy.write("generated init script")
        initpy.close()

        # here comes the hoop to jump through to get our
        # seleniumrcconfig on the python path of a zope2instance
        # script by making it an egg
        setuppy = open(seleniumrcsetuppath,'w')
        setuppy.write("""
from setuptools import setup
setup(name='seleniumrcconfig', version='1', py_modules=['seleniumrcconfig'],
      entry_points={'zc.buildout': ['default = recipe:Recipe']},
     )
""")
        setuppy.close()
        from zc.buildout import easy_install
        easy_install.install(['seleniumrcconfig'],
                             'develop-eggs',
                             links=['file://%s#egg=seleniumrcconfig-dev' %(self.options['location'])])
        return dest

    def update(self):
        pass
